# myadmin/views.py 中定义如下视图
import json
import os
import time
import oss2
import uuid
import shutil
# import pandas
import datetime
import pandas as pd
from django.db.transaction import atomic
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from libs.utils.ajax import ajax_ok, ajax_fail
from libs.utils.com_func import Struct
from django.core.paginator import Paginator
from libs.tl_models.turing.anyang.models import TeachingArrangement, ExpArrangement, PracticeArrangement, \
    Subject, MarkResult, CourseAverageScore
from django.contrib.auth import authenticate, login, get_user_model
from myadmin.common.common import processing_data
User = get_user_model()


@csrf_exempt
@atomic()
def get_mark_result(request):
    """
        接口功能说明：管理员获取所有督导老师打分结果
        --------------------------------------------
        接口逻辑说明：管理员可以根据打分切换排序，可以更具教师
        姓名，和课程类型查询数据
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/dataDetail/get/mark/result/?user_id=1&page=1  1 管理员获取所有督导老师打分结果
        @apiGroup dataDetail
        @apiName get_mark_result

        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {Int}        course_type              课程类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
        @apiParam     {Int}        start_time               开始实践（时间戳， 如若要选实践开始实践时必须存在的）
        @apiParam     {Int}        end_time                 结束时间（时间戳） 结束实践不选择默认传当前时间戳
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "teacher_name": "王老师",
          "course_type": 1,
          "start_time": 1,
          "end_time": 1
        }
        
        @apiSuccess {Int}      result_id                     结果ID
        @apiSuccess {Int}      arrange_id                    排课ID
        @apiSuccess {Int}      week_num                      周数
        @apiSuccess {Int}      type                          课程类型 1 理论 2 实验 （现在接口值返回实验，理论，后面可能如果添加返回字段可能会增加)3 实践 4体育 5艺术技法 6外语课 7艺术理论
        @apiSuccess {Int}      all_people_num                应到人数
        @apiSuccess {Int}      attendance                    实到人数
        @apiSuccess {Int}      gross_score                   总分数

        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "mark_result_list":[
                    {
                        "result_id":1,
                        "arrange_id":12,
                        "teacher_name":"王老师",
                        "type":1,
                        "week_num":1,
                        "all_people_num":1,
                        "attendance":1,
                        "evaluate":"评价",
                        "remark":"备注",
                        "image_url":"http://image....",
                        "question_result":[
                            {
                                "question":"题干",
                                "score":"9.5"
                            }
                        ],
                        "gross_score":"34.5"
                        "add_time":"创建时间"
                        "supervisor_name":"督导老师姓名"
                        "department":"部门"
                        "course":"课程"
                        "semester":"学期"
                        "class_no":"上课班号"
                        "section":"节次"
                        "site":"地点"
                    }
                ]
            },
            "response": "ok"
        }
    """
    page = int(request.GET.get("page", 1))          # 页码
    post = json.loads(request.body, strict=False)
    course_type = int(post.get('course_type'))      # 课程类型
    teacher_type = int(post.get('teacher_type'))    # 搜索老师类型 1 搜素教师 2搜做督导老师
    teacher_name = post.get('teacher_name')         # 教师姓名
    start_time = int(post.get('start_time'))        # 开始实践（时间戳， 如若要选实践开始实践时必须存在的）
    end_time = int(post.get('end_time'))            # 结束时间（时间戳） 结束实践不选择默认传当前时间戳

    if course_type and teacher_name != "" and start_time:
        print("课程类型和教师姓名和时间都存在")
        if teacher_type == 1:
            result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name, add_time__gte=start_time,
                                              add_time__lte=end_time, type=course_type).\
                values("id", "arrange_id", "teacher_name", "type", "user_id","week_num", "all_people_num",
                       "attendance", "evaluate","remark","image_url", "question_result", "gross_score", "add_time", "update_time").\
                order_by("gross_score")
        else:
            result_list = MarkResult.objects.filter(supervisor_name=teacher_name, add_time__gte=start_time,
                                                    add_time__lte=end_time, type=course_type). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                       "update_time"). \
                order_by("gross_score")
    elif teacher_name != "" and course_type:
        print("课程类型和教师姓名存在")
        if teacher_type == 1:
            result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name, type=course_type). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
                order_by("gross_score")
        else:
            result_list = MarkResult.objects.filter(supervisor_name=teacher_name, type=course_type). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                       "update_time"). \
                order_by("gross_score")
    elif course_type and start_time:
        print("课程类型和时间存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(type=course_type, add_time__gte=start_time,
                                          add_time__lte=end_time). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
            order_by("gross_score")
    elif teacher_name != "" and start_time:
        print("教师姓名和时间存在")
        # 标题模糊搜索
        if teacher_type == 1:
            result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name, add_time__gte=start_time,
                                              add_time__lte=end_time). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
                order_by("gross_score")
        else:
            result_list = MarkResult.objects.filter(supervisor_name=teacher_name, add_time__gte=start_time,
                                                    add_time__lte=end_time). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                       "update_time"). \
                order_by("gross_score")

    elif start_time:
        print("时间存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(add_time__gte=start_time, add_time__lte=end_time). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
            order_by("gross_score")
    elif teacher_name != "":
        print("教师姓名存在")
        # 标题模糊搜索
        if teacher_type == 1:
            result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
                order_by("gross_score")
        else:
            result_list = MarkResult.objects.filter(supervisor_name=teacher_name). \
                values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                       "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                       "update_time"). \
                order_by("gross_score")
    elif course_type:
        print("课程存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(type=course_type). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
            order_by("gross_score")
    else:
        print("======hello")
        result_list = MarkResult.objects.filter(). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time", "update_time"). \
            order_by("gross_score")
    print(result_list,'======dasd')
    data = Struct()
    if result_list:
        paginator = Paginator(result_list, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            result_list = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            result_list = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            result_list = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录

        arrange_ids = [x.get("arrange_id") for x in result_list]

        teaching_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') in [1,4,5,6,7]]
        exp_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') == 2]
        pra_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') == 3]
        teaching_arrang_list = list(TeachingArrangement.objects.filter(id__in=teaching_arrange_ids). \
                                    values("id", "type", "department", "course", "teacher_name", "semester", "class_no",
                                           "section", "site"))

        exp_arrang_list = list(ExpArrangement.objects.filter(id__in=exp_arrange_ids). \
                               values("id", "type", "department", "course", "teacher_name", "semester", "class_no",
                                      "section", "site"))
        practicea_arrang_list = list(PracticeArrangement.objects.filter(id__in=pra_arrange_ids). \
                               values("id", "type", "department", "course", "teacher_name", "semester", "site"))
        arrang_list = teaching_arrang_list + exp_arrang_list + practicea_arrang_list

        # arrang_obj = PracticeArrangement.objects.filter(id__in=arrange_ids). \
        #     values("id", "department", "course", "teacher_name", "semester", "week_time")
        # pass
        # 后面在家

        user_ids = [x.get("user_id") for x in result_list]
        user_list = User.objects.filter(id__in=user_ids).values('supervisor_name', 'rank', 'id')
        num = 1
        mark_result_list = []
        print(result_list,'=rererererewrerere')
        for obj in result_list:
            row = Struct()
            row.result_id = obj.get("id")                           # 结果ID
            row.arrange_id = obj.get("arrange_id")                  # 排课ID
            row.teacher_name = obj.get("teacher_name")              # 教师姓名
            row.type = obj.get("type")                              # 课程类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
            row.week_num = obj.get("week_num")                      # 周数
            row.all_people_num = obj.get("all_people_num")          # 应到人数
            row.attendance = obj.get("attendance")                  # 实到人数
            row.arrival_rate = '{:.0%}'.format(int(row.attendance)/int(row.all_people_num))         # 到课率
            row.evaluate = obj.get("evaluate")                      # 评价
            row.remark = obj.get("remark")                          # 备注
            row.image_url = obj.get("image_url")                    # 现场图片
            row.question_result = obj.get("question_result")        # 打分详情
            row.gross_score = obj.get("gross_score")                # 总分数
            row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(obj.get("add_time")))                      # 创建时间

            supervisor_obj = next((x for x in user_list
                                  if x.get("id") == obj.get("user_id")), "")  # 督导老师姓名
            row.supervisor_name = ""
            row.rank = 0
            if supervisor_obj:
                row.supervisor_name = supervisor_obj.get('supervisor_name', '')
                row.rank = supervisor_obj.get('rank', 0)

            arrang_obj = next((x for x in arrang_list if x.get("id") == row.arrange_id and row.type==x.get('type')), None)
            if not arrang_obj:
                continue
            row.department = arrang_obj.get("department", '')       # 部门
            row.course = arrang_obj.get("course", '')               # 课程
            row.semester = arrang_obj.get("semester", '')           # 学期
            row.class_no = arrang_obj.get("class_no", '')           # 上课班号
            row.section = arrang_obj.get("section", '')             # 节次
            row.site = arrang_obj.get("site", '')                   # 地点
            mark_result_list.append(row)
    else:
        mark_result_list = []
        total_page = 0
        page = 0
    data.mark_result_list = mark_result_list    # 结果列表
    data.total_page = total_page                # 总页码
    data.current_page = page                    # 页码
    return ajax_ok(data)

@csrf_exempt
@atomic()
def export_excel_result(request):

    post = json.loads(request.body, strict=False)
    course_type = int(post.get('course_type'))  # 课程类型
    teacher_name = post.get('teacher_name')  # 教师姓名
    start_time = int(post.get('start_time'))  # 开始实践（时间戳， 如若要选实践开始实践时必须存在的）
    end_time = int(post.get('end_time'))  # 结束时间（时间戳） 结束实践不选择默认传当前时间戳
    if course_type and teacher_name != "null" and start_time:
        print("课程类型和教师姓名和时间都存在")
        result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name, add_time__gte=start_time,
                                                add_time__lte=end_time, type=course_type). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif teacher_name != "null" and course_type:
        print("课程类型和教师姓名存在")
        result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name, type=course_type). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif course_type and start_time:
        print("课程类型和时间存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(type=course_type, add_time__gte=start_time,
                                                add_time__lte=end_time). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif teacher_name != "null" and start_time:
        print("教师姓名和时间存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name, add_time__gte=start_time,
                                                add_time__lte=end_time). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif start_time:
        print("时间存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(add_time__gte=start_time, add_time__lte=end_time). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif teacher_name != "null":
        print("教师姓名存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(teacher_name__icontains=teacher_name). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif course_type:
        print("课程存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(type=course_type). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    else:
        print(444444)
        result_list = MarkResult.objects.filter(). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")

    data = Struct()
    if result_list:
        arrange_ids = [x.get("arrange_id") for x in result_list]
        if course_type == 1:  # 理论
            arrang_list = TeachingArrangement.objects.filter(id__in=arrange_ids). \
                values("id", "department", "course", "teacher_name", "semester", "class_no", "section", "site")
        elif course_type == 2:  # 实践
            arrang_list = ExpArrangement.objects.filter(id__in=arrange_ids). \
                values("id", "department", "course", "teacher_name", "semester", "class_no", "section", "site")
        else:
            teaching_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') == 1]
            exp_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') == 2]
            teaching_arrang_list = list(ExpArrangement.objects.filter(id__in=teaching_arrange_ids). \
                                        values("id", "department", "course", "teacher_name", "semester", "class_no",
                                               "section", "site"))
            exp_arrang_list = list(ExpArrangement.objects.filter(id__in=exp_arrange_ids). \
                                   values("id", "department", "course", "teacher_name", "semester", "class_no",
                                          "section", "site"))
            arrang_list = teaching_arrang_list + exp_arrang_list
            # arrang_obj = PracticeArrangement.objects.filter(id__in=arrange_ids). \
            #     values("id", "department", "course", "teacher_name", "semester", "week_time")
            # pass
            # 后面在家

        user_ids = [x.get("user_id") for x in result_list]
        user_list = User.objects.filter(id__in=user_ids).values('supervisor_name', 'id')
        mark_result_list = []
        for obj in result_list:
            row = Struct()
            type = obj.get("type")  # 课程类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
            my_type = "理论 " if type == 1 else "实验" if type == 2 else "实践" if type == 3 \
                else "体育" if type == 4 else "艺术技法" if type == 5 else "外语课" if type == 6 else "艺术理论"
            supervisor_name = next((x.get('supervisor_name') for x in user_list
                                        if x.get("id") == obj.get("user_id")), "")  # 督导老师姓名
            arrang_obj = next((x for x in arrang_list if x.get("id") == row.arrange_id), None)
            if not arrang_obj:
                continue
            mark_result_list.append([obj.get("id"), obj.get("arrange_id"), obj.get("teacher_name"),
                                     my_type, obj.get("week_num"), obj.get("all_people_num"),
                                     obj.get("attendance"), obj.get("evaluate"), obj.get("remark"),
                                     obj.get("image_url"), obj.get("question_result"), obj.get("gross_score"),
                                     obj.get("add_time"), supervisor_name, arrang_obj.get("department", ''),
                                     arrang_obj.get("course", ''), arrang_obj.get("semester", ''), arrang_obj.get("class_no", ''),
                                     arrang_obj.get("section", ''), arrang_obj.get("site", '')])

        # df = pd.DataFrame(mark_result_list)
        # # df.drop_duplicates()
        # df.columns = ['结果ID', '排课ID', '教师姓名', '课程类型', '周数', '应到人数',
        #               '实到人数', '评价', '备注', '现场图片', '打分详情', '总分数',
        #               '创建时间', '督导老师姓名', '部门', '课程', '学期', '上课班号', '节次', '地点']
        # df.to_excel(os.path.join(r"C:\Users\Administrator\Desktop\anyang\anyang\cms\myadmin\result1.xlsx"), index_label="ID")
        data = Struct()
        data.mark_result_list = mark_result_list
    return ajax_ok(data)

@csrf_exempt
@atomic()
def course_average_score(request):
    page = int(request.GET.get("page", 1))  # 页码
    post = json.loads(request.body, strict=False)
    teacher_name = post.get('teacher_name')  # 教师姓名
    print("wwwwww")
    if teacher_name != "null":
        print("教师姓名存在")

        courseaveragescore = CourseAverageScore.objects.filter(teacher_name__icontains="[20160280]翟雁"). \
            values("id", "arrange_id", "teacher_name", "first_super", "two_super", "type", 'add_time')
    else:
        courseaveragescore = CourseAverageScore.objects.filter(). \
            values("id", "arrange_id", "teacher_name", "first_super", "two_super", "type", 'add_time')

    data = Struct()
    if courseaveragescore:
        paginator = Paginator(courseaveragescore, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            courseaveragescore = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            courseaveragescore = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            courseaveragescore = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录

        average_score_list = []
        for obj in courseaveragescore:
            row = Struct()
            row.id = obj.get('id')
            row.arrange_id = obj.get('arrange_id')  # 课程ID
            row.teacher_name = obj.get('teacher_name', '')  # 老师姓名
            row.course_name = obj.get('course_name', '')  # 课程名
            row.type = obj.get('type')  # 课程类型
            row.add_time = obj.get('add_time')  # 创建时间
            row.first_super = json.loads(obj.get('first_super'))  # 一级督导打分详情 列:[12,34]
            row.two_super = json.loads(obj.get('two_super'))  # 二级督导打分详情
            first_super_avg_score = sum(row.first_super) / len(row.first_super)
            two_super_avg_score = sum(row.two_super) / len(row.two_super)

            row.avg_score = first_super_avg_score + two_super_avg_score  # 平均分

            average_score_list.append(row)
    else:
        average_score_list = []
        total_page = 0
        page = 0
    data.average_score_list = average_score_list  # 结果列表
    data.total_page = total_page  # 总页码
    data.current_page = page  # 页码
    return ajax_ok(data)

@csrf_exempt
@atomic()
def supervisor_mark_result(request):
    """
        接口功能说明：督导老师获取所有督导老师打分结果
        --------------------------------------------
        接口逻辑说明：督导老师获取所有督导老师打分结果
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/dataDetail/supervisor/mark/result/?user_id=1&page=1  2 督导老师获取所有督导老师打分结果
        @apiGroup dataDetail
        @apiName supervisor_mark_result

        @apiParam     {Int}        course_type              课程类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
        @apiParam     {Int}        start_time               开始实践（时间戳， 如若要选实践开始实践时必须存在的）
        @apiParam     {Int}        end_time                 结束时间（时间戳） 结束实践不选择默认传当前时间戳
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "course_type": 1,
          "start_time": 1,
          "end_time": 1
        }


        @apiSuccess {Int}      result_id                     结果ID
        @apiSuccess {Int}      arrange_id                    排课ID
        @apiSuccess {Int}      week_num                      周数
        @apiSuccess {Int}      type                          课程类型 1 理论 2 实验 （现在接口值返回实验，理论，后面可能如果添加返回字段可能会增加)3 实践 4体育 5艺术技法 6外语课 7艺术理论
        @apiSuccess {Int}      all_people_num                应到人数
        @apiSuccess {Int}      attendance                    实到人数
        @apiSuccess {Int}      gross_score                   总分数

        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "mark_result_list":[
                    {
                        "result_id":1,
                        "arrange_id":12,
                        "teacher_name":"王老师",
                        "type":1,
                        "week_num":1,
                        "all_people_num":1,
                        "attendance":1,
                        "evaluate":"评价",
                        "remark":"备注",
                        "image_url":"http://image....",
                        "question_result":[
                            {
                                "question":"题干",
                                "score":"9.5"
                            }
                        ],
                        "gross_score":"34.5"
                        "add_time":"创建时间"
                        "department":"部门"
                        "course":"课程"
                        "semester":"学期"
                        "class_no":"上课班号"
                        "section":"节次"
                        "site":"地点"
                    }
                ]
            },
            "response": "ok"
        }
    """
    page = int(request.GET.get("page", 1))          # 页码
    user_id = int(request.GET.get("user_id"))       # 督导老师user_id
    post = json.loads(request.body, strict=False)
    course_type = int(post.get('course_type'))      # 课程类型
    start_time = int(post.get('start_time'))        # 开始实践（时间戳， 如若要选实践开始实践时必须存在的）
    end_time = int(post.get('end_time'))            # 结束时间（时间戳） 结束实践不选择默认传当前时间戳
    if course_type and start_time:
        print("课程类型和时间都存在")
        result_list = MarkResult.objects.filter(add_time__gte=start_time, user_id=user_id,
                                                add_time__lte=end_time, type=course_type). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif course_type:
        print("课程类型存在")
        result_list = MarkResult.objects.filter(type=course_type, user_id=user_id). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    elif start_time:
        print("时间存在")
        # 标题模糊搜索
        result_list = MarkResult.objects.filter(add_time__gte=start_time, user_id=user_id,
                                                add_time__lte=end_time). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    else:
        result_list = MarkResult.objects.filter(user_id=user_id). \
            values("id", "arrange_id", "teacher_name", "type", "user_id", "week_num", "all_people_num",
                   "attendance", "evaluate", "remark", "image_url", "question_result", "gross_score", "add_time",
                   "update_time"). \
            order_by("gross_score")
    data = Struct()
    if result_list:
        paginator = Paginator(result_list, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            result_list = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            result_list = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            result_list = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录

        arrange_ids = [x.get("arrange_id") for x in result_list]
        if course_type in [1,4,5,6,7]:
            arrang_list = TeachingArrangement.objects.filter(id__in=arrange_ids). \
                values("id", "department", "course", "teacher_name", "semester", "class_no", "section", "site")
        elif course_type == 2:  # 实践
            arrang_list = ExpArrangement.objects.filter(id__in=arrange_ids). \
                values("id", "department", "course", "teacher_name", "semester", "class_no", "section", "site")
        else:
            teaching_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') == [1,4,5,6,7]]
            exp_arrange_ids = [x.get("arrange_id") for x in result_list if x.get('type') == 2]
            teaching_arrang_list = list(ExpArrangement.objects.filter(id__in=teaching_arrange_ids).\
                values("id", "department", "course", "teacher_name", "semester", "class_no", "section", "site"))
            exp_arrang_list = list(ExpArrangement.objects.filter(id__in=exp_arrange_ids).\
                values("id", "department", "course", "teacher_name", "semester", "class_no", "section", "site"))
            arrang_list = teaching_arrang_list + exp_arrang_list
            # print(arrang_list,'=dasdasdasdasd')
            # arrang_obj = PracticeArrangement.objects.filter(id__in=arrange_ids). \
            #     values("id", "department", "course", "teacher_name", "semester", "week_time")
            # pass
            # 后面在家
        mark_result_list = []
        for obj in result_list:
            row = Struct()
            row.result_id = obj.get("id")  # 结果ID
            row.arrange_id = obj.get("arrange_id")  # 排课ID
            row.teacher_name = obj.get("teacher_name")  # 教师姓名
            row.type = obj.get("type")  # 课程类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
            row.week_num = obj.get("week_num")  # 周数
            row.all_people_num = obj.get("all_people_num")  # 应到人数
            row.attendance = obj.get("attendance")  # 实到人数
            row.evaluate = obj.get("evaluate")  # 评价
            row.remark = obj.get("remark")  # 备注
            row.image_url = obj.get("image_url")  # 现场图片
            row.question_result = obj.get("question_result")  # 打分详情
            row.gross_score = obj.get("gross_score")  # 总分数
            row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(obj.get("add_time"))) # 创建时间
            arrang_obj = next((x for x in arrang_list if x.get("id") == row.arrange_id), None)
            if not arrang_obj:
                continue
            row.department = arrang_obj.get("department", '')  # 部门
            row.course = arrang_obj.get("course", '')  # 课程
            row.semester = arrang_obj.get("semester", '')  # 学期
            row.class_no = arrang_obj.get("class_no", '')  # 上课班号
            row.section = arrang_obj.get("section", '')  # 节次
            row.site = arrang_obj.get("site", '')  # 地点
            mark_result_list.append(row)
    else:
        mark_result_list = []
        total_page = 0
        page = 0
    data.mark_result_list = mark_result_list  # 结果列表
    data.total_page = total_page  # 总页码
    data.current_page = page  # 页码
    return ajax_ok(data)



# 教师分数
@csrf_exempt
@atomic()
def teacher_mark(request):
    page = int(request.GET.get("page", 1))  # 页码
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    department_name = post.get("department_name")      # 教师姓名
    start_time = post.get("start_time")          # 开始时间
    end_time = post.get("end_time")              # 结束时间
    if department_name and start_time: # 时间 教师姓名都存在
        mark_scores = MarkResult.objects.filter(department_name__icontains=department_name, add_time__gte=start_time,
                                          add_time__lte=end_time).values("id", "teacher_name", "department_name", "arrange_id", "type", "user_id", "gross_score")
    elif department_name:
        mark_scores = MarkResult.objects.filter(department_name__icontains=department_name).values("id", "teacher_name", "department_name", "arrange_id", "type", "user_id",
                                                                               "gross_score")
    elif start_time: # 只存在时间
        mark_scores = MarkResult.objects.filter(add_time__gte=start_time,
                                                add_time__lte=end_time).values("id", "teacher_name", "department_name", "arrange_id", "type", "user_id",
                                                                               "gross_score")
    else:  # 都不存在
        mark_scores = MarkResult.objects.filter().values("id", "teacher_name", "department_name", "arrange_id", "type", "user_id", "gross_score")

    new_mark_scores = processing_data(mark_scores, "teacher_name")

    data = Struct()
    if new_mark_scores:
        paginator = Paginator(new_mark_scores, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            new_mark_scores = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            new_mark_scores = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            new_mark_scores = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录
        mark_scores_list = []
        num = 1
        for obj in new_mark_scores:
            row = Struct()
            row.num = num  # 序号
            row.user_id = obj.get("id")                                 # 用户id
            row.teacher_name = obj.get("teacher_name")                 # 教师姓名
            row.department_name = obj.get("department_name", "")       # 院系
            row.type = obj.get("type")                                 # 课程类别
            row.gross_score = obj.get("gross_score")                   # 阶段平均分平均分
            num += 1
            mark_scores_list.append(row)
    else:
        mark_scores_list = []
        total_page = 0
        page = 0

    data.weixin_users = mark_scores_list  # 小程序用户列表
    data.total_page = total_page      # 总页码
    data.current_page = page          # 页码
    return ajax_ok(data)


# 督导老师听课次数
@csrf_exempt
@atomic()
def supervision_class_num(request):
    page = int(request.GET.get("page", 1))  # 分页页码
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    supervisor_name = post.get("supervisor_name", '')             # 督导教师姓名
    if supervisor_name:
        teacher_users = User.objects.filter(is_active=1, supervisor_name__icontains=supervisor_name).values("id", "supervisor_name",
                                                                                       "username", "password", "rank", "date_joined").order_by("id")
    else:
        teacher_users = User.objects.filter(is_active=1).values("id", "supervisor_name",
                                                                "username", "password", "rank", "date_joined").order_by("id")
    data = Struct()
    if teacher_users:
        paginator = Paginator(teacher_users, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            teacher_users = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            teacher_users = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            teacher_users = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录
        class_list = []
        supervisor_ids = [x.get("id") for x in teacher_users]
        mark_result = MarkResult.objects.filter(user_id__in=supervisor_ids).values("teacher_name", 'user_id')
        for obj in teacher_users:
            row = Struct()
            try:
                row.user_id = obj.get("id")  # 督导id
                row.supervisor_name = obj.get("supervisor_name", '')  # 督导老师姓名
                row.username = obj.get("username")  # 用户名
                row.rank = obj.get("rank")  # 级别
                mark_result_list = [x.get("teacher_name") for x in mark_result if x.get("user_id") == row.user_id]
                row.all_class_num = len(mark_result_list)
                teacher_list = []
                name_list = []
                for x in mark_result_list:
                    tmp = dict()
                    if x in name_list:
                        for obj in teacher_list:
                            if x == obj.get("teacher_name"):
                                obj["class_num"] = obj.get("class_num") + 1
                        continue
                    tmp["teacher_name"] = x
                    tmp["class_num"] = 1
                    name_list.append(x)
                    teacher_list.append(tmp)
                row.teacher_list = teacher_list
                class_list.append(row)
            except:
                continue
    else:
        class_list = []
        total_page = 0
        page = 0

    data.class_list = class_list  # 小程序用户列表
    data.total_page = total_page      # 总页码
    data.current_page = page          # 页码
    return ajax_ok(data)



# 督导老师听课次数
@csrf_exempt
@atomic()
def change_score(request):
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    mark_result_id = int(post.get("mark_result_id", 0))  # 打分结果id
    gross_score = int(post.get("gross_score", 0))       # 分数
    mark_result_obj = MarkResult.objects.filter(id=mark_result_id).last()
    if mark_result_obj:
        mark_result_obj.gross_score = gross_score
        mark_result_obj.save()
    else:
        return ajax_fail(message="数据不存在")
    return ajax_ok()



# 督导老师督导多少老师
@csrf_exempt
@atomic()
def supervisors_number(request):
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    page = int(post.get("page", 1))                                 # 页码
    supervisor_name = post.get("supervisor_name", "")      # 督导老师姓名
    if supervisor_name: # 时间 教师姓名都存在
        mark_scores = MarkResult.objects.filter(teacher_name__icontains=supervisor_name).values("id","supervisor_name", "user_id", "type", "teacher_name", "arrange_id")
    else:  # 都不存在
        mark_scores = MarkResult.objects.filter().values("id","supervisor_name", "user_id", "teacher_name", "type", "arrange_id")

    # new_mark_scores = processing_data(mark_scores, "teacher_name")

    data = Struct()
    if mark_scores:
        paginator = Paginator(mark_scores, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            mark_scores = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            mark_scores = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            mark_scores = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录
        mark_list = []
        s_name_id_list = []
        for obj in mark_scores:
            row = Struct()
            row.id = obj.get("id")
            row.supervisor_name = obj.get("supervisor_name")
            row.arrange_id = obj.get("arrange_id")
            t_name_list = [y.get("teacher_name") for y in mark_scores if obj.get("supervisor_name") == y.get("supervisor_name")]
            row.people_all_num = len(list(set(t_name_list)))
            teacher_list = []
            name_list = []
            for z in t_name_list:
                tmp = dict()
                if z in name_list:
                    for obj in teacher_list:
                        if z == obj.get("teacher_name"):
                            obj["class_num"] = obj.get("class_num") + 1
                    continue
                tmp["teacher_name"] = z
                tmp["class_num"] = 1
                teacher_list.append(tmp)
                name_list.append(z)
            if obj.get("user_id") in tuple(s_name_id_list):
                continue
            row.teacher_list = teacher_list
            try:
                if obj.get("type") in [1,4,5,6,7]: # 理论
                    course_name = TeachingArrangement.objects.filter(id=obj.get("arrange_id", 0)).last().course
                elif obj.get("type") == 2:  # 实验
                    course_name = ExpArrangement.objects.filter(id=obj.get("arrange_id", 0)).last().course
                else: # 实践
                    course_name = PracticeArrangement.objects.filter(id=obj.get("arrange_id", 0)).last().course
            except:
                course_name = ""
            row.course_name = course_name
            s_name_id_list.append(obj.get("user_id"))
            class_all_num = 0
            for cobj in teacher_list:
                class_all_num += cobj.get("class_num")
            row.class_all_num = class_all_num
            mark_list.append(row)
    else:
        mark_list = []
        total_page = 0
        page = 0
    sur_name_list = []
    new_mark_list = []

    data.mark_list = mark_list  # 小程序用户列表
    data.total_page = total_page      # 总页码
    data.current_page = page          # 页码
    return ajax_ok(data)


@csrf_exempt
@atomic()
def delete_mark_result(request):
    result_id = request.GET.get("result_id", 0)  # 类别ID
    MarkResultObj = MarkResult.objects.filter(id=result_id)
    if MarkResultObj:  # 删除
        MarkResultObj.delete()
    else:
        return ajax_fail(message="删除数据不存在")
    return ajax_ok()


@csrf_exempt
@atomic()
def subject_list(request):
    """
    接口功能说明：题库列表
    --------------------------------------------
    接口逻辑说明：题库列表
    --------------------------------------------
    修改人        修改时间        修改原因
    --------------------------------------------
    张凯           2020-9-22	   创建
    --------------------------------------------
    """
    """
    @api {post} /admin/dataDetail/subject/list/?user_id=1  3 题库列表（题库列表）
    @apiGroup dataDetail
    @apiName subject_list

   @apiParam     {Int}           subject_type         题库类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论 (下拉选)
   @apiParam     {Int}           page                 页码
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "subject_type":1,
        "page":1,
    }

    @apiSuccess {List}     subject_list                     用户列表
    @apiSuccess {Int}           subject_list.quesion_id         试题id
    @apiSuccess {String}        subject_list.quesion            题干
    @apiSuccess {String}        subject_list.source_value       分值
    @apiSuccess {String}        subject_list.type               题库类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论 (对应数字显示汉字)
    @apiSuccess {String}        subject_list.add_time           创建时间
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "data":{
            "id":12,
            "quesion":"..........",
            "source_value":"15",
            "type":1,
            "add_time":"2020-12-12 14:20:50"
        },
        "response": "ok",
        "data": "",
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body, strict=False)

    subject_type = post.get('subject_type', 0)  # 督导名称
    page = post.get('page')  # 页码
    if subject_type:
        subjects = Subject.objects.filter(type__icontains=subject_type).values("id", "quesion", "source_value",
                                                                               "type", "add_time")
    else:
        subjects = Subject.objects.filter().values("id", "quesion", "source_value", "type", "add_time")

    data = Struct()
    if subjects:
        paginator = Paginator(subjects, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            subjects = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            subjects = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            subjects = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录
        subject_list = []
        num = 1
        for obj in subjects:
            try:
                row = Struct()
                row.num = num  # 序号
                row.quesion_id = obj.get("id")  # 试题id
                row.quesion = obj.get("quesion", '')  # 题干
                row.source_value = obj.get("source_value")  # 分值
                row.type = obj.get("type")  # 题库类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论 (下拉选)
                row.add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(obj.get("add_time")))  # 创建时间
                subject_list.append(row)
                num += 1
            except:
                continue
    else:
        subject_list = []
        total_page = 0
        page = 0
    data.subject_list = subject_list  # 文章列表
    data.total_page = total_page  # 总页码
    data.current_page = page  # 页码
    return ajax_ok(data)


@csrf_exempt
@atomic()
def change_subject(request):
    """
    接口功能说明：修改试题
    --------------------------------------------
    接口逻辑说明：修改试题
    --------------------------------------------
    修改人        修改时间        修改原因
    --------------------------------------------
    张凯           2020-9-22	   创建
    --------------------------------------------
    """
    """
    @api {post} /admin/dataDetail/subject/list/?user_id=1 4 题库列表（修改试题）
    @apiGroup dataDetail
    @apiName change_subject

    @apiParam     {Int}                 quesion_id                    试题id
    @apiParam     {String}              quesion                       题干
    @apiParam     {String}              source_value                  分值
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "quesion_id":1,
        "quesion":"1244545",
        "source_value":1555",
    }
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "data":{
        },
        "response": "ok",
        "data": "",
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    quesion_id = post.get("quesion_id")
    quesion = post.get("quesion", "")
    source_value = post.get("source_value", 0)

    subject_obj = Subject.objects.filter(id=quesion_id)
    now = int(time.time())
    if subject_obj:  # 更新
        try:
            subject_obj.update(
                **{"quesion": quesion, "source_value": source_value, "update_time": now})
        except:
            return ajax_fail(message="更新失败，请检查输入数据")
    else:
        return ajax_fail(message="数据不存在")
    return ajax_ok()